from invidious import *
import requests
import sys

from plugins.plugin import Plugin

sys.path.append("..")
from src.video import Video as RVideo
from src.channel import Channel
from src.playlist import Playlist

from src.history import History
from src.config import Config

class InvidiousSearch(Plugin):

    def __init__(self, history: History=History(), config: Config=Config) -> None:
        super().__init__(history, config)

        self.history = history
        self.config = config

        self.name = "[+] Invidious: Search"
        self.category = "Invidious"

        self.query_description = """You can input args (separate they with &).
    page: number of page.
    sort_by: [relevance, rating, upload_date, view_count].
    date: [hour, today, week, month, year].
    duration: [short, long].
    type: [video, playlist, channel, all] (default: video).
    feauters: [hd, subtitles, creative_commons, 3d, live, purchased, 4k, 360, location, hdr].
    region: ISO 3166 country code (default: US).

    Example: distrotube&date=hour 
"""

        self.params = {
            'query'     : True,
            'page'      : False,
            'sort_by'   : False,
            'date'      : False,
            'duration'  : False,
            'type'      : False,
            'feauters'  : False,
            'region'    : False
        }

        self.flag = "-is"
        self.full_flag = "--ivsearch"
        self.flag_help = "search videos from invidious by query"
        self.flag_action = ""
    
    def get_search(self, query: str=""):
        srch = self.invidious.search(query)

        items = []
        for sr in srch:
            if type(sr) == ChannelItem:
                sr = self.invidious.get_channel(sr.authorId)
                sr.convert(Channel)
                vids = list()
                for video in sr.latestVideos:
                    video.convert(RVideo)
                    video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
                    video.isWatched = video.in_history(self.history)
                    vids.append(video.to_json())
                sr.latestVideos = vids
            elif type(sr) == VideoItem:
                sr.convert(RVideo)
                sr.url = self.invidious.get_working_mirror() + "/watch?v=" + sr.videoId
                sr.isWatched = sr.in_history(self.history)
            elif type(sr) == PlaylistItem:
                sr.convert(Playlist)
                vids = list()
                for video in sr.videos:
                    video.convert(RVideo)
                    video.url = self.invidious.get_working_mirror() + "/watch?v=" + video.videoId
                    video.isWatched = video.in_history(self.history)
                    vids.append(video.to_json())
                sr.videos = vids
            else: continue
            item = sr.to_json()

            items.append(item)

        return items

    def get_items(self, params):
        query = ""
        if 'query' in params: 
            query = params['query']
        return self.get_search(query)


